﻿using Database.Exceptions;
using Database.Repositories;
using GameLogic.Exceptions;
using GameLogic.Place;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GameLogic
{
    /// <summary>
    /// Handles operations regarding the Game.
    /// Examples are starting a game, adding a Character to que to a game, and so on.
    /// 
    /// All operations before, after and outside of the game 
    /// should be done through this manager.
    /// </summary>
    public class GameManager
    {
        private readonly IslandManager _islandManager;
        private readonly IslandQueManager _islandQueManager;

        private readonly IslandRepository _islandRepository;
        private readonly CharacterRepository _characterRepository;

        public GameManager()
        {
            _islandManager = new IslandManager();
            _islandQueManager = new IslandQueManager();

            _islandRepository = new IslandRepository();
            _characterRepository = new CharacterRepository();
        }

        public Guid InitGame(Guid characterId)
        {
            if (_characterRepository.Read(characterId) == null)
                return Guid.Empty;

            var islandId = _islandManager.CreateIsland();

            _islandQueManager.AddCharacterToQue(islandId, characterId);

            return islandId;
        }

        public bool JoinGame(Guid characterId, Guid islandId)
        {
            // Control that Island exists
            var islandExists = (_islandRepository.Read(islandId) != null);
            if (!islandExists)
                throw new EntityDoesNotExistException("Island");

            // Control that Character exists
            var characterExists = (_characterRepository.Read(characterId) != null);
            if(!characterExists)
                throw new EntityDoesNotExistException("Character");
            
            // Control that Island is not full
            var islandIsFull = _islandManager.IsFull(islandId);
            if (islandIsFull)
                throw new ValidationFailedException("Island is full");

            // Put character in que
            _islandQueManager.AddCharacterToQue(islandId, characterId);

            // Return ok-message
            return true;
        }
    }
}
